#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

pthread_mutex_t g_mutex = PTHREAD_MUTEX_INITIALIZER; 
#define MUTEXLOCK() pthread_mutex_lock(&g_mutex);
#define MUTEXUNLOCK() pthread_mutex_unlock(&g_mutex);

int g_lock_line = 0;
#define LOCK_WITH_DLDETECT(mutex, lock_line)						\
	do {                                                            \
		int i = 0;                                              \
									\
		while (pthread_mutex_trylock(&mutex)) {                   \
			if (i++ >= 50) {                               \
				fprintf(stderr, "#### deadlock detected! location:[%s][%s][%d], last lock occured in line %d####\n", \
				       __FILE__, __func__, __LINE__, lock_line); \
				i = 0;                                  \
			}                                               \
			usleep(100 * 1000);                             \
		}                                                       \
		lock_line = __LINE__;				\
	} while (0)
	
int dead_lock_simulation()
{
    LOCK_WITH_DLDETECT(g_mutex, g_lock_line);
    LOCK_WITH_DLDETECT(g_mutex, g_lock_line);
    return 0;
}

int dynamic_init_lock()
{
	int ret =0;
	pthread_mutex_t mutex;
	if ( (ret = pthread_mutex_init(&mutex, NULL)) < 0) {
		fprintf(stderr, "pthread_mutex_init failed, error:%s\r\n", strerror(errno));
		ret = -1;
	}
	pthread_mutex_destroy(&mutex);
	return ret;
}

int main()
{
	dead_lock_simulation();
	dynamic_init_lock();
	return 0;
}
